package com.cc.dlnalib;

import android.util.Log;

import org.cybergarage.xml.Attribute;
import org.cybergarage.xml.Node;
import org.cybergarage.xml.ParserException;
import org.cybergarage.xml.parser.XmlPullParser;

public class StateParser {
    private static final String TAG = "StateParser";
    private static final String STATE_TAG = "TransportState";
    private static final String DURATION_TAG = "CurrentMediaDuration";
    private static final String AV_TRANSPORT_URI = "AVTransportURI";
    private final EventCallback eventCallback;

    public StateParser(EventCallback eventCallback) {
        this.eventCallback = eventCallback;
    }

    private String url;
    private String duration;

    public void parse(String xml) {
        if (xml == null) {
            Log.e(TAG, "parse: xml is null.");
            return;
        }
        XmlPullParser parser = new XmlPullParser();
        try {
            Node node = parser.parse(xml);
            Node instanceID = node == null ? null : node.getNode("InstanceID");
            if (instanceID == null) {
                return;
            }
            if (xml.contains(STATE_TAG)) {
                Node stateNode = instanceID.getNode("TransportState");
                Attribute attribute = stateNode.getAttribute("val");
                if (attribute != null) {
                    String state = attribute.getValue();
                    Log.i(TAG, "parse: " + state);
                    if (eventCallback != null) {
                        eventCallback.onStateChanged(state == null ? DLNAControllerKt.STATE_STOPPED : state);
                    }
                }
            }
            if (xml.contains(DURATION_TAG)) {
                Node durationNode = instanceID.getNode(DURATION_TAG);
                if (durationNode != null) {
                    Attribute attribute = durationNode.getAttribute("val");
                    if (attribute != null) {
                        duration = attribute.getValue();
                    }
                }
            }
            if (xml.contains(AV_TRANSPORT_URI)) {
                Node durationNode = instanceID.getNode(AV_TRANSPORT_URI);
                if (durationNode != null) {
                    url = getNodeValue(durationNode);
                }
            }
        } catch (ParserException e) {
            e.printStackTrace();
        }
    }

    private static String getNodeValue(Node node) {
        if (node != null) {
            Attribute attribute = node.getAttribute("val");
            if (attribute != null) {
                return attribute.getValue();
            }
        }
        return null;
    }

    public interface EventCallback {
        void onStateChanged(String state);
    }

    public String getUrl() {
        return url;
    }

    public String getDuration() {
        return duration;
    }

    public void reset() {
        url = null;
        duration = null;
    }
}
